/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteCadastra.java
 *
 * Created on 06/06/2011, 22:17:54
 */

package pacote;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;

/**
 *
 * @author Pardall
 */
public class UserSisAltera extends javax.swing.JFrame {

    private EntityManager em;
    private short id;

    /** Creates new form ClienteCadastra */
    public UserSisAltera(EntityManager exem) {
        initComponents();
        this.em = exem;

        List<Admin> adm = findAllAdmin();
        Object[] nomes = fillNomes(adm);
        String login = (String)JOptionPane.showInputDialog(null,
                            "Nome do usuário",
                            "Selecione um usuário",
                            JOptionPane.INFORMATION_MESSAGE,
                            null,
                            nomes,
                            nomes[0]);
        findId(login,adm);
        fillForm();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        alterar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tblogin = new javax.swing.JTextField();
        tbConfSenha = new javax.swing.JPasswordField();
        jLabel10 = new javax.swing.JLabel();
        tbSenha = new javax.swing.JPasswordField();
        cbNivel = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Cadastrar Cliente");
        setResizable(false);

        alterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/check.png"))); // NOI18N
        alterar.setText("Alterar");
        alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alterarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/editar.png"))); // NOI18N
        jLabel1.setText("Alteração de Usuário de Sistema");

        jLabel6.setText("Confirmar:");

        jLabel4.setText("Senha:");

        jLabel2.setText("Login:");

        tblogin.setMaximumSize(new java.awt.Dimension(150, 20));
        tblogin.setMinimumSize(new java.awt.Dimension(150, 20));
        tblogin.setPreferredSize(new java.awt.Dimension(150, 20));
        tblogin.setRequestFocusEnabled(false);

        jLabel10.setText("Nível:");

        cbNivel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Funcionário" }));
        cbNivel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbNivelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel10)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tbConfSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                            .addComponent(cbNivel, javax.swing.GroupLayout.Alignment.TRAILING, 0, 229, Short.MAX_VALUE)
                            .addComponent(tbSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                            .addComponent(tblogin, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(alterar, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tblogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tbSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(tbConfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbNivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addGap(18, 18, 18)
                .addComponent(alterar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterarActionPerformed
        if (evt.getSource() == this.alterar){
            
            em.getTransaction().begin();

            Admin adm = em.find(Admin.class, id);
            if(Arrays.equals(tbSenha.getPassword(), tbConfSenha.getPassword())){

                adm.setLgoin(tblogin.getText());
                adm.setSenha(new String(tbSenha.getPassword()));
                adm.setNivel(cbNivel.getSelectedIndex());

                em.getTransaction().commit();

                JOptionPane.showMessageDialog(null, "Usuário alterado.");

                this.dispose();

            } else {
                JOptionPane.showMessageDialog(null, "Senhas não conferem.");
            }
        }
    }//GEN-LAST:event_alterarActionPerformed

    private void cbNivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbNivelActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_cbNivelActionPerformed

    private Object[] fillNomes (List<Admin> adm){
        List<String> nomes = new ArrayList<String>();
        for (Admin a : adm){
            nomes.add(a.getLogin());
        }
        return nomes.toArray();
    }

    private void fillForm (){
        Admin a = em.find(Admin.class, this.id);

        this.tblogin.setText(a.getLogin());
        this.tbSenha.setText(a.getSenha());
        this.tbConfSenha.setText(a.getSenha());
        this.cbNivel.setSelectedIndex(a.getNivel());

    }

    private void findId (String login, List<Admin> adm){
        for (Admin a : adm){
            if (a.getLogin().equals(login)){
                this.id = a.getId();
                break;
            }
        }
    }

    private List<Admin> findAllAdmin (){
        TypedQuery<Admin> query = em.createNamedQuery("Admin.findAll", Admin.class);
       return query.getResultList();

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton alterar;
    private javax.swing.JComboBox cbNivel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPasswordField tbConfSenha;
    private javax.swing.JPasswordField tbSenha;
    private javax.swing.JTextField tblogin;
    // End of variables declaration//GEN-END:variables

}